import React, { useState } from 'react';
import { Card, Form, Input, Button, Typography, message, Row, Col } from 'antd';
import { UserOutlined, LockOutlined, MailOutlined, PhoneOutlined } from '@ant-design/icons';
import { Link, useNavigate } from 'react-router-dom';
import { register, login } from '../api/divide/user/sdk.gen';
import { useAuthStore } from '../store/authStore';

const { Title, Text } = Typography;

const Register: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();
  const { setUser, setLoading: setAuthLoading } = useAuthStore();

  const handleRegister = async (values: {
    username: string;
    email: string;
    phone: string;
    password: string;
    confirmPassword: string;
  }) => {
    setLoading(true);
    setAuthLoading(true);
    
    try {
      // 注册
      const registerResponse = await register({
        body: {
          username: values.username,
          email: values.email,
          phone: values.phone,
          password: values.password,
          confirmPassword: values.confirmPassword,
        },
      });

      if (registerResponse.data?.data) {
        message.success('注册成功！正在为您自动登录...');
        
        // 自动登录
        const loginResponse = await login({
          body: {
            usernameOrEmail: values.username,
            password: values.password,
            rememberMe: false,
          },
        });

        if (loginResponse.data?.data) {
          const user = loginResponse.data.data;
          setUser(user);
          message.success('注册并登录成功！');
          navigate('/');
        }
      } else {
        message.error(registerResponse.data?.message || '注册失败');
      }
    } catch (error: any) {
      message.error(error.response?.data?.message || '注册失败，请检查输入信息');
    } finally {
      setLoading(false);
      setAuthLoading(false);
    }
  };

  return (
    <div style={{ 
      minHeight: '100vh', 
      display: 'flex', 
      alignItems: 'center', 
      justifyContent: 'center',
      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
      padding: 20
    }}>
      <Row justify="center" style={{ width: '100%' }}>
        <Col xs={24} sm={16} md={12} lg={8} xl={6}>
          <Card style={{ 
            boxShadow: '0 8px 32px rgba(0,0,0,0.1)',
            borderRadius: 12,
            backdropFilter: 'blur(10px)',
            backgroundColor: 'rgba(255,255,255,0.95)'
          }}>
            <div style={{ textAlign: 'center', marginBottom: 24 }}>
              <Title level={2} style={{ color: '#1890ff', marginBottom: 8 }}>
                创建账号
              </Title>
              <Text type="secondary">加入Redis学习平台，开始您的学习之旅</Text>
            </div>

            <Form
              form={form}
              layout="vertical"
              onFinish={handleRegister}
              size="large"
            >
              <Form.Item
                name="username"
                label="用户名"
                rules={[
                  { required: true, message: '请输入用户名' },
                  { min: 3, max: 20, message: '用户名长度为3-20个字符' },
                  { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线' }
                ]}
              >
                <Input 
                  prefix={<UserOutlined />} 
                  placeholder="请输入用户名"
                  maxLength={20}
                />
              </Form.Item>

              <Form.Item
                name="email"
                label="邮箱"
                rules={[
                  { required: true, message: '请输入邮箱' },
                  { type: 'email', message: '请输入有效的邮箱地址' }
                ]}
              >
                <Input 
                  prefix={<MailOutlined />} 
                  placeholder="请输入邮箱"
                  maxLength={50}
                />
              </Form.Item>

              <Form.Item
                name="phone"
                label="手机号"
                rules={[
                  { required: true, message: '请输入手机号' },
                  { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' }
                ]}
              >
                <Input 
                  prefix={<PhoneOutlined />} 
                  placeholder="请输入手机号"
                  maxLength={11}
                />
              </Form.Item>

              <Form.Item
                name="password"
                label="密码"
                rules={[
                  { required: true, message: '请输入密码' },
                  { min: 6, max: 20, message: '密码长度为6-20个字符' }
                ]}
              >
                <Input.Password 
                  prefix={<LockOutlined />} 
                  placeholder="请输入密码"
                  maxLength={20}
                />
              </Form.Item>

              <Form.Item
                name="confirmPassword"
                label="确认密码"
                dependencies={['password']}
                rules={[
                  { required: true, message: '请确认密码' },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (!value || getFieldValue('password') === value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error('两次输入的密码不一致'));
                    },
                  }),
                ]}
              >
                <Input.Password 
                  prefix={<LockOutlined />} 
                  placeholder="请再次输入密码"
                  maxLength={20}
                />
              </Form.Item>

              <Form.Item>
                <Button 
                  type="primary" 
                  htmlType="submit" 
                  loading={loading}
                  block
                  size="large"
                  style={{ 
                    height: 48,
                    fontSize: 16,
                    fontWeight: 500
                  }}
                >
                  注册
                </Button>
              </Form.Item>

              <div style={{ textAlign: 'center', marginTop: 16 }}>
                <Text>已有账号？ <Link to="/login">立即登录</Link></Text>
              </div>
            </Form>
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default Register;